package com.async.demo.model;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
@Slf4j
public class QueueListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private  MockQueue mockQueue;

    @Autowired
    private  DeferredResultHolder deferredResultHolder;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

        new Thread( ()->{
                while (true){
                    // 有值
                    if(!StringUtils.isEmpty(mockQueue.getCompleteOrder())){
                        String orderNum = mockQueue.getCompleteOrder();
                        log.info("返回订单处理结果：" +  orderNum);
                        // 设置返回的处理结果
                        deferredResultHolder.getMap().get(orderNum).setResult("place order success");
                        mockQueue.setCompleteOrder(null);
                    }else{
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        ).start();


    }
}
